package com.whz.generic.parameter;

import lombok.experimental.UtilityClass;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * spel分析器辅助类
 *
 * @author whz
 *  2021/8/13
 */
@UtilityClass
public class ExpressionParserUtils {
    private final Map<Object, ExpressionParser> map = new ConcurrentHashMap<>();

    /**
     * 从目标对象解析SPEL表达式
     *
     * @param expressionString spel表达式:支持#root.xxx或者#简单类名.xxx
     * @param target           目标对象
     * @return 表达式的值
     */
    public Object parseExpression(String expressionString, Object target) {
        return getTmcExpressionParser(target).parseExpression(expressionString);
    }

    public <T> T parseExpression(String expressionString, Object target, Class<T> desiredResultType) {
        return getTmcExpressionParser(target).parseExpression(expressionString, desiredResultType);
    }

    private ExpressionParser getTmcExpressionParser(Object target) {
        ExpressionParser parser = map.get(target);
        if (parser == null) {
            parser = new ExpressionParser(target);
            map.put(target, parser);
        }
        return parser;
    }
}
